package cc.wd.demo.blockchain.model;

import cc.wd.demo.blockchain.BlockChainApplication;

import java.security.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wudi
 * @date 2018/8/29
 */
public class Wallet {
    private PrivateKey privateKey;
    private PublicKey publicKey;
    public HashMap<String,TransactionOutput> UTXOs = new HashMap<>(); //钱包自身的UTXO

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public Wallet() throws NoSuchAlgorithmException {
        generateKeyPair();
    }

    public void generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(512, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        privateKey = keyPair.getPrivate();
        // 得到公钥
        publicKey = keyPair.getPublic();
    }

    //返回余额并保存钱包自身的UTXO
    public float getBalance() {
        float total = 0;
        for (Map.Entry<String, TransactionOutput> item: BlockChainApplication.UTXOs.entrySet()){
            TransactionOutput UTXO = item.getValue();
            if(UTXO.isMine(publicKey)) { //查看输出是否属于我即货币是不是我的
                UTXOs.put(UTXO.id,UTXO); //添加到未使用的交易列表中
                total += UTXO.value ;
            }
        }
        return total;
    }

}
